package cn.thinkluck.pattern.prototype.deep;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 播放列表
 * 递归深拷贝示例
 */
@Data
public class Playlist implements Cloneable {
    private Long id;
    private String name;
    private List<Song> songs = new ArrayList<>();

    public Playlist() {
    }

    //深拷贝播放列表
    @Override
    public Playlist clone() {
        try {
            Playlist clone = (Playlist) super.clone();
            clone.songs = new ArrayList<>();
            clone.name = new String(name);
            clone.id = new Long(id);
            songs.forEach(song -> {
                clone.songs.add(new Song(song.getTitle(), song.getArtist()));
            });
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    //深拷贝播放列表
    public Playlist(Playlist sourcePlayList) {
        this.id = sourcePlayList.getId();
        this.name = sourcePlayList.getName();
        this.songs = sourcePlayList.getSongs();
    }


    public static void main(String[] args) {
        Playlist playlist = new Playlist();
        playlist.setId(1L);
        playlist.setName("杰伦");
        playlist.songs.add(new Song("稻香", "杰伦"));
        playlist.songs.add(new Song("迷迭香", "杰伦"));
        playlist.songs.add(new Song("七里香", "杰伦"));
        // 浅拷贝后的最喜爱的专辑
        Playlist favouriteList = playlist.clone();
        favouriteList.songs.add(new Song("曹操", "林俊杰"));
        System.out.println(favouriteList);
        //可以看到深拷贝后的最喜爱的专辑和原专辑的歌单不是同一个对象
        System.out.println(playlist.id==favouriteList.id);
        System.out.println(playlist.name==favouriteList.name);
        System.out.println(playlist.songs.get(0));
        System.out.println(favouriteList.songs.get(0));
    }
}
